//
//  JDToast.swift
//  readtool
//
//  Created by WanJiading on 16/6/12.
//  Copyright © 2016年 DAD. All rights reserved.
//

import UIKit

class JDToast: NSObject {
    static let showingDurationPercentChar: Double       = 0.12      // 每个字符显示的时长

    static var toast: JDToastView? = nil
	
	static var toastShowingTime: CGFloat!
	
	private static var _minShowTime: Double = 0
	/// 提示语最小显示时间
	static var minShowTime: Double {
		set (newValue) {
			_minShowTime = newValue
			_maxShowTime = 0
			_showTime = 0
		}
		get {
			return _minShowTime
		}
	}
	
	private static var _maxShowTime: Double = 0
	/// 提示语最大显示时间
	static var maxShowTime: Double {
		set (newValue) {
			_minShowTime = 0
			_maxShowTime = newValue
			_showTime = 0
		}
		get {
			return _maxShowTime
		}
	}
	
	private static var _showTime: Double = 0
	/// 提示语显示时间
	static var showTime: Double {
		set (newValue) {
			_minShowTime = 0
			_maxShowTime = 0
			_showTime = newValue
		}
		get {
			return _showTime
		}
	}

    class func show(_ message: String) {

        toast?.removeFromSuperview()

        let toastView = JDToastView(message: message)
        toast = toastView

        SharedApplication.keyWindow!.addSubview(toastView)
		
		let messageLength = Double(message.count)
		var duration = showingDurationPercentChar * messageLength
		
		if minShowTime > 0 && duration < minShowTime {
			duration = minShowTime
		}
		
		if maxShowTime > 0 && duration > maxShowTime {
			duration = maxShowTime
		}
		
		if showTime > 0 {
			duration = showTime
		}
//		toastView.alpha = 0
        UIView.animate(withDuration: 0.25, animations: {
            toastView.alpha = 1
            }, completion: { (_) in
 
                UIView.animateKeyframes(withDuration: 0.25,
                                                    delay: TimeInterval(duration),
                                                    options: UIViewKeyframeAnimationOptions.allowUserInteraction,
                                                    animations: {
                                                        toastView.alpha = 0
                                                    }, completion: { (_) in
                                                        toastView.removeFromSuperview()
														_minShowTime = 0
														_maxShowTime = 0
														_showTime = 0
                                                })
        })
    }
	
	
	/// 显示提示
	///
	/// - parameter message:  提示语
	/// - parameter duration: 持续时间(秒)
	class func show(_ message: String, _ duration: Double) {
		self.showTime = duration
		show(message)
	}
	
}
